//
//  LS_RefreshControl.swift
//  weibo
//
//  Created by 罗李苏 on 16/5/28.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

//创建自定义刷新工具中的枚举
enum RefreshStatus{
    case Normal     //普通状态
    case Pulling    //准备刷新状态
    case Refreshing //正在刷新
}

private let refreshViewHeight: CGFloat = 60
class LS_RefreshControl: UIControl {
    
    var status:RefreshStatus = .Normal{
        didSet{
            switch status {
            case .Normal:
                print("下拉起飞")
                //隐藏箭头
                arrowicon.hidden = false
                
                tipLabel.text = "哥要起飞"
                //箭头的形变回复
//                UIView.animateWithDuration(0.25, animations: { 
//                    
                
//                })
                self.indicatorView.stopAnimating()
                UIView.animateWithDuration(0.25, animations: {
                    self.arrowicon.transform = CGAffineTransformIdentity
                    }, completion: { (_) in
                        //转动小菊花
                        
                })
                
//                
                if oldValue == .Refreshing{
                    UIView.animateWithDuration(0.25, animations: {
                        //必须之前的状态是 refreshing才能减
                        //scrollView的顶部的距离 创造悬停的效果
                        var inset = self.scrollView!.contentInset
                        //增加刷新的控件的高度
                        inset.top -= refreshViewHeight
                        //赋值给scrollView
                        self.scrollView?.contentInset = inset
                    })

                }

                
                
                
            case .Pulling:
                print("准备起飞")
                tipLabel.text = "准备起飞"
                //箭头发生形变
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
                
            case .Refreshing:
                print("正在刷新")
                tipLabel.text = "正在起飞"
                arrowicon.hidden = true
                //转动小菊花
                indicatorView.startAnimating()
                //MARK:请求网络数据 给观察的对象主动发送对应类型的事件
                sendActionsForControlEvents(.ValueChanged)
                UIView.animateWithDuration(0.25, animations: {
                    //scrollView的顶部的距离 创造悬停的效果
                    var inset = self.scrollView!.contentInset
                    //增加刷新的控件的高度
                    inset.top += refreshViewHeight
                    //赋值给scrollView
                    self.scrollView?.contentInset = inset
                })


            }
        
        }
    
    }

    func endRefreshing(){
        //延时执行
        let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.6))
        dispatch_after(time_t, dispatch_get_main_queue()) {
            self.status = .Normal
        }
    }
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshViewHeight, width: ScreenWidth, height: refreshViewHeight)
        
        super.init(frame: rect)
        backgroundColor = UIColor.yellowColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK:加载UI
    private func setupUI(){
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)
        //添加约束
        arrowicon.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        tipLabel.snp_makeConstraints { (make) in
            make.left.equalTo(arrowicon.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        indicatorView.snp_makeConstraints { (make) in
            make.center.equalTo(arrowicon)
        }
    
    }
    
    //MARK:重写将要移动到父视图上这个方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //获取tableView
        if let myFather = newSuperview as? UIScrollView {
            //如果父视图是scrollView及其子类
            //获取父视图的垂直方向的位移
            // KVO  通过键值方式观察对象的属性变化
            scrollView = myFather
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }

    }
    //MARK:键值观察的响应方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //1.获取父视图的垂直方向的位移
        let offset = scrollView?.contentOffset.y ?? 0
        //2. 和 -124 比较
        if scrollView!.dragging {//被拽动
            //被拽动的过程与 -124 作比较
            if status == .Pulling && offset > -124 {
                //普通状态
                status = .Normal
            }else if status == .Normal && offset < -124 {
                //达到临界点 变为等待刷新状态
                status = .Pulling
            }

        }else{
            //没有被拽动 && 并且状态是 等待刷新状态 修改为刷新状态
            if status == .Pulling {
                status = .Refreshing
            }

        }
    }
    //懒加载子视图
    //记录父视图的属性
    var scrollView: UIScrollView?
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel: UILabel = UILabel(title: "下拉起飞", font: 14, textColor: UIColor.darkGrayColor())
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    
    deinit {
        //移除键值观察
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
